﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TomNet.App.Core.Contracts;
using TomNet.App.Model.DB;
using TomNet.SqlSugarCore.Entity;

namespace TomNet.App.Web.Service
{
	public class DAL
	{
        private readonly IUnitOfWork _unitOfWork;

        public DAL(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        #region decimal UserElectricityBalance(int userId) 用户电费余额。

        /// <summary>
        /// 用户电费余额。
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        public decimal UserElectricityBalance(int userId)
        {
            decimal result = 0;

            var query = _unitOfWork.DbContext.Queryable<UserElectricity>()
                .Where(p => p.UserId == userId)
                .Sum(p => (decimal?)p.Amount);

            result = query.GetValueOrDefault();

            return result;
        }

		#endregion

		#region List<int> GetAfterUserIds(int userId) 获取指定用户所有下级用户的Id集合。

		/// <summary>
		/// 获取指定用户所有下级用户的Id集合。
		/// </summary>
		/// <param name="userId"></param>
		/// <returns></returns>
		public List<int> GetAfterUserIds(int userId)
		{
			List<int> result = new List<int>();
			
			var query = _unitOfWork.DbContext.Queryable<App.Model.DB.Identity.Users, App.Model.DB.Identity.UserMap>(
				(a, b) => a.Id == b.UserId)
				.Where((a, b) => ((b.SuperId == userId
					|| b.SuperSalesmanId == userId
					|| b.InterfaceId == userId
					|| b.InterfaceSalesmanId == userId
					|| b.AgentId == userId
					|| b.AgentSalesmanId == userId))
					&& !a.IsDeleted)
				.Select((a, b) => a.Id);

			result = query.ToList();
			return result;
		}

		#endregion

		#region List<int> GetAfterBusinessIds(int userId) 获取指定用户所有下级用户的订单。

		/// <summary>
		/// 获取指定用户所有下级用户的订单。
		/// </summary>
		/// <param name="userId">用户Id</param>
		/// <returns></returns>
		public List<int> GetAfterBusinessIds(int userId)
		{
			//用户角色表
			//1超级管理员 2公司业务 3接口商 4接口商下的业务员 5代理商 6代理商下的业务员 7用户

			List<int> result = new List<int>();

			int roleId = _unitOfWork.DbContext.Queryable<App.Model.DB.Identity.Users>().Where(p => p.Id == userId).Select(p => p.RoleID).First();
			if (roleId <= 0)
				return result;

			var query = _unitOfWork.DbContext.Queryable<Business, App.Model.DB.Identity.UserMap>(
				(a, b) => a.UserId == b.UserId)
				.Where((a, b) => (roleId == 1 && b.SuperId == userId)
					|| (roleId == 2 && b.SuperSalesmanId == userId)
					|| (roleId == 3 && b.InterfaceId == userId)
					|| (roleId == 4 && b.InterfaceSalesmanId == userId)
					|| (roleId == 5 && b.AgentId == userId)
					|| (roleId == 6 && b.AgentSalesmanId == userId))
				.OrderBy((a, b) => a.CreatedTime)
				.Select((a, b) => a.Id);

			result = query.ToList();
			return result;
		}

		#endregion
	}
}
